package com.javabi.common.concurrent.lock;

import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * A non thread safe lock factory that uses weak keys. Use of this factory assumes keys have a longer life than the
 * locks they use. Useful where there is a huge number of keys, but only a subset of them in use at any given time. Keys
 * that are no longer referenced will allow their associated locks to be released from memory.
 */
public class WeakLockFactory<K> implements ILockFactory<K> {

	private final boolean fair;
	private final Map<K, Lock> map;

	public WeakLockFactory(boolean fair) {
		this.fair = fair;
		this.map = new WeakHashMap<K, Lock>();
	}

	@Override
	public Lock getLock(K key) {
		if (key == null) {
			throw new NullPointerException("key");
		}

		Lock lock = map.get(key);
		if (lock == null) {
			lock = new ReentrantLock(fair);
			map.put(key, lock);
		}

		return lock;
	}

}
